package com.yunshang.shoppingmall.ShopTask;
import com.yunshang.shoppingmall.Methods.FinaceMethods;
import com.yunshang.shoppingmall.common.MessageConstants;
import com.yunshang.shoppingmall.common.Response;
import com.yunshang.shoppingmall.common.UserRequest;
import com.yunshang.shoppingmall.common.weixin.WeChat;
import com.yunshang.shoppingmall.entity.*;
import com.yunshang.shoppingmall.service.*;
import com.yunshang.shoppingmall.service.Finace.FinaceService;
import com.yunshang.shoppingmall.service.Finace.FinaceTotalService;
import com.yunshang.shoppingmall.service.User.UserRankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class OrderCheckDay {
    @Autowired
    OrderService orderService;
    @Autowired
    ConfigService configService;
    @Autowired
    CartService cartService;
    @Autowired
    FinaceService finaceService;
    @Autowired
    FinaceTotalService finaceTotalService;
    @Autowired
    SysUserNoService sysUserNoService;
    @Autowired
    UserRankService userRankService;
    @Autowired
    UserNoAchievementService userNoAchievementService;
    @Autowired
    OrderCheckService orderCheckService;
    @Scheduled(cron="0 0 03 * * ?")//每天凌晨3点
    public void fixedDelay() {
        String ip = "";//0:0:0:0:0:0:0:1
        if (!ip.equals("0:0:0:0:0:0:0:1")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = new Date();
            String date = sdf.format(date1);
            Date dateX = addDateMinut(date, -24);
            List<Order> list = orderService.selectOrderCheck(dateX);
            Set<String> set = new HashSet();
            if (list != null && list.size() > 0) {
                for (Order order : list) {
                    if (order != null) {
                        String orderStatus = order.getOrderStatus() == null ? "0" : order.getOrderStatus();
                        int checkCount = order.getCheckCount() == null ? 0 : order.getCheckCount();
//                    if(checkCount<3) {//只检查3次
                        if (orderStatus.equals("701") || orderStatus.equals("706")) {
                            try {
                                Response bool = deal(order);
                                Boolean j = (Boolean) bool.getData();   //这里必须强制转换，否则编译报错。
                                if (j == false) {
                                    int coun = checkCount + 1;
                                    order.setCheckCount(coun);
                                    order.setOldSpqk(bool.getErrorDetail());
                                    orderService.updateByPrimaryKeySelective(order);
                                    set.add("false:" + order.getOrderNo());
                                } else {
                                    set.add("true:" + order.getOrderNo());
                                }
                            } catch (Exception e) {
                                order.setOldSpqk(e.getMessage());
                                orderService.updateByPrimaryKeySelective(order);
                            }
//                        }
                        }
                    }
                }
                try {
                    String logNos = "";
                    if (set != null && set.size() > 0) {
                        List<String> list1 = new ArrayList<>(set);
                        for (int f = 0; f < list1.size(); f++) {
                            if (f == (list1.size() - 1)) {
                                logNos += list1.get(f);
                            } else {
                                logNos += list1.get(f) + ",";
                            }
                            String s = null;
                        }
                    }
                    com.yunshang.shoppingmall.entity.OrderCheck orderCheck = new com.yunshang.shoppingmall.entity.OrderCheck();
                    orderCheck.setOrderNos(logNos);
                    orderCheck.setTime(new Date());
                    orderCheckService.insertSelective(orderCheck);
                } catch (Exception e) {
                    com.yunshang.shoppingmall.entity.OrderCheck orderCheck = new com.yunshang.shoppingmall.entity.OrderCheck();
                    orderCheck.setOrderNos(e.getMessage());
                    orderCheck.setTime(new Date());
                    orderCheckService.insertSelective(orderCheck);
                }
            }
        }
    }

    public Response deal(Order order) throws Exception {
        double getFreight=order.getFreight()==null?0:order.getFreight().doubleValue();
        double getRealPay=order.getRealPay()==null?0:order.getRealPay();
        double getInter=order.getInter()==null?0:order.getInter().doubleValue();
        double getCostInter=order.getCostInter()==null?0:order.getCostInter().doubleValue();
        String error="";
        boolean orderbool=false;
        String cash1=(getRealPay+getFreight-getInter-getCostInter)+"";
        boolean bools1= WeChat.getOrder(order.getOrderNo(),cash1);
        if(bools1){
            String orderNo=order.getOrderNo();
            Config config=configService.selectByPrimaryKey(1);
            String userNoId1="";
            if(order.getUserId()!=null){
                userNoId1=order.getUserId().toString();
            }else {
                Cart cart=cartService.selectByOrderNo(orderNo).get(0);
                if(cart!=null){
                    userNoId1=cart.getUserId().toString();
                }
            }

            UserNo userNoSS=sysUserNoService.selectByPrimaryKey(Integer.parseInt(userNoId1));

            String cash=cash1;
            double balance=0;
            int userNoId=Integer.parseInt(userNoId1);
            FinaceTotal finaceTotal=finaceTotalService.selectFinaceBalaceAll(userNoId);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            String date1 = sdf.format(date);

            UserNo userNo1 = userNoSS;

            int memberUserId = 0,memberLevel = 0,ids = 0,userNoReCommendId=0;//推荐人id
            UserRank  userRank=null;
            UserRank recommendUserRank=null;//推荐人的等级
            UserNo recommendUserNo=null;
            int recommendRankId=0;
            double recommendCommission=0.00;
            if (userNo1 != null) {
                memberUserId = userNo1.getId();//用户编号ID
                memberLevel = userNo1.getRank();
                userNoReCommendId=userNo1.getRecommend();
                recommendUserNo=sysUserNoService.selectByPrimaryKey(userNoReCommendId);
                userRank=userRankService.selectByPrimaryKey(memberLevel);//用户等级
                if(recommendUserNo!=null){
                    recommendRankId=recommendUserNo.getRank();
                    recommendUserRank=userRankService.selectByPrimaryKey(recommendRankId);
                    if(recommendUserRank!=null){
                        recommendCommission=recommendUserRank.getCommission();
                    }
                }
            }
            //推荐人积分
            double recommendBalance=0.00;
            int recommendFId=0;
            FinaceTotal f=new FinaceTotal();
            f.setfType("1");
            f.setUserId(userNoReCommendId);
            FinaceTotal recommendFinaceTotal = FinaceMethods.selectFinaceBalace(f); //推荐人积分
            if(recommendFinaceTotal!=null){
                recommendFId=recommendFinaceTotal.getfId();
                recommendBalance=recommendFinaceTotal.getBalance();
            }
            double amount;
            Boolean strResult = cash.matches("-?[0-9]+.*[0-9]*");
            if(strResult==false){
                amount=0;
            }else {
                amount=Double.parseDouble(cash);
            }

            if(amount>0){//现金支付是否大于0
                FinaceToData finaceToData = new FinaceToData();
                finaceToData.setUserId(userNoId);//用户编号Id
                finaceToData.setFinaceType("777");
                finaceToData.setRemark("充值"+orderNo);
                finaceToData.setClassify(1);
                finaceToData.setFinaceTime(Timestamp.valueOf(date1));//时间
                finaceToData.setAmount(BigDecimal.valueOf(amount));//积分
                //用户积分的余额
                finaceToData.setBalance(BigDecimal.valueOf(finaceTotal.getBalance1() + amount));
                finaceToData.setOpratorUId(userNoId);
                int res = finaceService.insertFinaceData(finaceToData);
                if(res<=0){
                    error +="充值失败!";
                }else {
                    orderbool = true;
                }
            }
            BigDecimal amount1;
            if(order.getRealPay()!=null&&order.getFreight()!=null){
                Boolean strResult1 = order.getRealPay().toString().matches("-?[0-9]+.*[0-9]*");
                Boolean strResult2 = order.getFreight().toString().matches("-?[0-9]+.*[0-9]*");
                if(strResult1==false||strResult2==false){
                    amount1=BigDecimal.valueOf(0);
                }else {
                    amount1=BigDecimal.valueOf(order.getRealPay()).add(order.getFreight());
                }
            }else {
                amount1=BigDecimal.valueOf(0);
            }
            if(amount1.doubleValue()>0){//实际支付总金额
                FinaceToData finaceToData1 = new FinaceToData();
                finaceToData1.setUserId(userNoId);//用户编号Id
                finaceToData1.setFinaceType("111");
                finaceToData1.setRemark("支出"+orderNo);
                finaceToData1.setClassify(1);
                finaceToData1.setFinaceTime(Timestamp.valueOf(date1));//时间
                BigDecimal costinter=order.getCostInter()==null?BigDecimal.valueOf(0):order.getCostInter();
                BigDecimal am=amount1.subtract(costinter);
                finaceToData1.setAmount(new BigDecimal(-am.doubleValue()));//积分
                balance=(finaceTotal.getBalance1()+amount+costinter.doubleValue())-amount1.doubleValue();
                finaceToData1.setBalance(BigDecimal.valueOf(balance));
                finaceToData1.setOpratorUId(userNoId);
                int res1 = finaceService.insertFinaceData(finaceToData1);
                if(res1<=0){
                    error +="添加充值记录失败!";
                }else {
                    //更新财务余额
                    FinaceTotal finaceTotal4=new FinaceTotal();
                    finaceTotal4.setOpratorId(userNoId);
                    finaceTotal4.setBalance(balance);
                    finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                    finaceTotal4.setOpratorUId(userNoId);
                    finaceTotal4.setUserId(userNoId);
                    finaceTotal4.setfType("1");
                    int cosRow;
                    if(finaceTotal.getfId1()>0){
                        finaceTotal4.setfId(finaceTotal.getfId1());
                        cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                    }else {
                        cosRow =finaceTotalService.insertSelective(finaceTotal4);
                    }
                    if (cosRow <= 0) {
                        error +="更新积分余额失败!";
                    }else {
                        orderbool = true;
                    }
                }
            }
            if(order.getCostInter()!=null){//订单实际支付使用的消费积分
                if(order.getCostInter().doubleValue()>0){
                    FinaceToData finaceToData2 = new FinaceToData();
                    finaceToData2.setUserId(userNoId);//用户编号Id
                    finaceToData2.setFinaceType("111");
                    finaceToData2.setRemark("支出"+orderNo);
                    finaceToData2.setClassify(4);
                    finaceToData2.setFinaceTime(Timestamp.valueOf(date1));//时间
                    BigDecimal amount2=order.getCostInter();
                    finaceToData2.setAmount(new BigDecimal(-amount2.doubleValue()));//
                    finaceToData2.setBalance(BigDecimal.valueOf((finaceTotal.getBalance4()) - amount2.doubleValue()));
                    finaceToData2.setOpratorUId(userNoId);
                    int res2 = finaceService.insertFinaceData(finaceToData2);
                    if(res2<=0){
                        //消费积分扣除有误
                        error +="消费积分记录添加有误";
                    }else {
                        //更新财务余额
                        FinaceTotal finaceTotal4=new FinaceTotal();
                        finaceTotal4.setfId(finaceTotal.getfId4());
                        finaceTotal4.setOpratorId(userNoId);
                        finaceTotal4.setBalance(((finaceTotal.getBalance4()) - amount2.doubleValue()));
                        finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                        finaceTotal4.setOpratorUId(userNoId);
                        finaceTotal4.setUserId(userNoId);
                        finaceTotal4.setfType("4");
                        int cosRow;
                        if(finaceTotal.getfId4()>0){
                            cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                        }else {
                            cosRow =finaceTotalService.insertSelective(finaceTotal4);
                        }
                        if (cosRow <= 0) {
                            error +="更新消费积分余额失败";
                        }else {
                            orderbool = true;
                        }
                    }
                }
            }
            if(order.getCoupon()!=null){
                if(order.getCoupon().doubleValue()>0){
                    FinaceToData finaceToData2 = new FinaceToData();
                    finaceToData2.setUserId(userNoId);//用户编号Id
                    finaceToData2.setFinaceType("111");
                    finaceToData2.setRemark("支出"+orderNo);
                    finaceToData2.setClassify(2);
                    finaceToData2.setFinaceTime(Timestamp.valueOf(date1));//时间
                    BigDecimal amount2=order.getCoupon();
                    finaceToData2.setAmount(new BigDecimal(-amount2.doubleValue()));//
                    finaceToData2.setBalance(BigDecimal.valueOf((finaceTotal.getBalance2()) - amount2.doubleValue()));
                    finaceToData2.setOpratorUId(userNoId);
                    int res2 = finaceService.insertFinaceData(finaceToData2);
                    if(res2<=0){
                        //购物券扣除有误
                        error +="购物券记录添加有误";
                    }else {
                        //更新财务余额
                        FinaceTotal finaceTotal4=new FinaceTotal();
                        finaceTotal4.setfId(finaceTotal.getfId2());
                        finaceTotal4.setOpratorId(userNoId);
                        finaceTotal4.setBalance(((finaceTotal.getBalance2()) - amount2.doubleValue()));
                        finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                        finaceTotal4.setOpratorUId(userNoId);
                        finaceTotal4.setUserId(userNoId);
                        finaceTotal4.setfType("2");
                        int cosRow;
                        if(finaceTotal.getfId2()>0){
                            cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                        }else {
                            cosRow =finaceTotalService.insertSelective(finaceTotal4);
                        }
                        if (cosRow <= 0) {
                            error +="更新购物券余额失败";
                        }else {
                            orderbool = true;
                        }
                    }
                }
            }
            if(order.getCashCoupon()!=null){
                if(order.getCashCoupon().doubleValue()>0){
                    FinaceToData finaceToData2 = new FinaceToData();
                    finaceToData2.setUserId(userNoId);//用户编号Id
                    finaceToData2.setFinaceType("111");
                    finaceToData2.setRemark("支出"+orderNo);
                    finaceToData2.setClassify(3);
                    finaceToData2.setFinaceTime(Timestamp.valueOf(date1));//时间
                    BigDecimal amount2=order.getCashCoupon();
                    finaceToData2.setAmount(new BigDecimal(-amount2.doubleValue()));//
                    finaceToData2.setBalance(BigDecimal.valueOf((finaceTotal.getBalance3()) - amount2.doubleValue()));
                    finaceToData2.setOpratorUId(userNoId);
                    int res2 = finaceService.insertFinaceData(finaceToData2);
                    if(res2<=0){
                        error +="代金券记录添加有误";
                        //代金券扣除有误
                        //throw new RuntimeException();
                    }else {
                        //更新财务余额
                        FinaceTotal finaceTotal4=new FinaceTotal();
                        finaceTotal4.setfId(finaceTotal.getfId3());
                        finaceTotal4.setOpratorId(userNoId);
                        finaceTotal4.setBalance(((finaceTotal.getBalance3()) - amount2.doubleValue()));
                        finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                        finaceTotal4.setOpratorUId(userNoId);
                        finaceTotal4.setUserId(userNoId);
                        finaceTotal4.setfType("3");
                        int cosRow;
                        if(finaceTotal.getfId3()>0){
                            cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                        }else {
                            cosRow =finaceTotalService.insertSelective(finaceTotal4);
                        }
                        if (cosRow <= 0) {
                            error +="更新代金券余额失败";
                        }else {
                            orderbool = true;
                        }
                    }
                }
            }
            //返还折扣券保存到数据库返finance3_table
            Integer cashCouponMul = 0;
            String financeName = "";
            if(config!=null){
                if(config.getCashcouponmul()!=null){
                    cashCouponMul = config.getCashcouponmul();//返折扣券的倍数 ---2倍
                }
                if(config.getFinacename3()!=""||config.getCashcouponmul()!=null){
                    financeName = config.getFinacename3();//返回----折扣券的名称
                }
            }
            if(cashCouponMul>0){
                int resf = FinaceMethods.insertFinaceU(3, BigDecimal.valueOf(order.getBackCashcoupon() * cashCouponMul), userNoId, order.getOrderNo() + "返" + financeName, userNoId, 999);
            }
            //更新会员等级
            if (memberLevel == 19) {
                userNo1.setRank(16);
                int resu = sysUserNoService.updateByPrimaryKeySelective(userNo1);
                if (resu <= 0) {
                    //日志or数据库

                }
            }
            order.setOrderStatus("702");
            order.setPayStatus("1");
            order.setPayTime(new Date());

            //添加记录运营成本到用户业绩表
            double opratorCost=0.00;//订单运营成本
            UserNoAchievement userNoAchievement=new UserNoAchievement();
            userNoAchievement.setOpratorCostSign("0");//为结算的业绩标志
            userNoAchievement.setUserNoId(memberUserId);
            userNoAchievement.setPayTime(new Timestamp(order.getpOrderTime().getTime()));
            if(order!=null&&order.getOpratorCost()!=null){
                order.getOpratorCost().doubleValue();
            }
            userNoAchievement.setOrderId(order.getOrderId());
            userNoAchievement.setOrderOpratorCost(opratorCost);
            if(opratorCost>0) {
//                int achievementRow = userNoAchievementService.insertSelective(userNoAchievement);
//                //添加记录运营成本到用户业绩表
//                if(achievementRow<=0){
//                    //error +="添加记录运营成本有误";
//                }
            }
            //分享赚
            if(userNoReCommendId<=0){//没有推荐人默认为零散会员编号id为62240
                userNoReCommendId=62240;
            }
            if(userNoReCommendId>0){//是否有推荐人
                double orderProfit=order.getOrderProfit();//订单利润
                double shareEaring=0.00;
                //System.out.println("recommendCommission:"+recommendCommission);
                //System.out.println(userRank.toString()+"----");
                if(recommendCommission-userRank.getCommission()>0){
                    shareEaring=orderProfit*(recommendCommission-userRank.getCommission())/100;
                }
                if(shareEaring>0){
                    FinaceToData finaceToDataRe = new FinaceToData();
                    finaceToDataRe.setUserId(userNoReCommendId);//推荐人用户编号Id
                    finaceToDataRe.setFinaceType("888");
                    finaceToDataRe.setRemark("分享赚"+orderNo);
                    finaceToDataRe.setClassify(1);
                    finaceToDataRe.setFinaceTime(Timestamp.valueOf(date1));//时间
                    finaceToDataRe.setAmount(new BigDecimal(shareEaring));//积分
                    finaceToDataRe.setBalance(new BigDecimal(shareEaring+recommendBalance));
                    finaceToDataRe.setOpratorUId(userNoReCommendId);
                    int row1 = finaceService.insertFinaceData(finaceToDataRe);
                    if(row1<=0){
                        error +="分享赚记录添加失败";
                    }
                    FinaceTotal finaceTotal4=new FinaceTotal();
                    finaceTotal4.setOpratorId(userNoReCommendId);
                    finaceTotal4.setBalance(recommendBalance+shareEaring);
                    finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                    finaceTotal4.setOpratorUId(userNoReCommendId);
                    finaceTotal4.setUserId(userNoReCommendId);
                    finaceTotal4.setfType("1");
                    int recommendF;
                    if(recommendFId>0){
                        finaceTotal4.setfId(recommendFId);
                        recommendF=finaceTotalService.updateByPrimaryKey(finaceTotal4);
                    }else {
                        recommendF=finaceTotalService.insertSelective(finaceTotal4);
                    }
                    if(recommendF<=0){
                        error +="分享赚积分余额更新失败";
                    }else {
                        orderbool = true;
                    }
                }

            }
            //分享赚

            orderService.activity(order,memberUserId+"",userRank.getCommission(),userNoReCommendId,balance);
            Integer res3=orderService.updateByPrimaryKeySelective(order);
            if(res3<=0){

            }
        }
        //return orderbool;
        return new Response(MessageConstants.MSG_SYS_ERROR,orderbool,error);
    }

    /**
     * 给时间加上几个小时
     * @param day 当前时间 格式：yyyy-MM-dd HH:mm:ss
     * @param hour 需要加的时间
     * @return
     */
    public Date addDateMinut(String day, int hour){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(day);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (date == null)
            return null;
        System.out.println("front:" + format.format(date)); //显示输入的日期
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.HOUR, hour);// 24小时制
        date = cal.getTime();
        System.out.println("after:" + format.format(date));  //显示更新后的日期
        cal = null;
        return date;

    }


}
